import React, { useContext } from 'react'

const ThemeContext = React.createContext({
  theme: 'light',
})

const MyContext = React.createContext({
  name: '默认用户',
  img: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp08%2F01042323313046.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649302276&t=0f0013c0cde234386852f0708fb943fe',
})

const Nav = () => {
  return (
    <>
      <h2>导航栏</h2>
      <UserAvatar />
      <UserLogin />
    </>
  )
}

class UserAvatar extends React.Component {
  static contextType = MyContext
  render() {
    console.log(this.context)
    return <img width={200} src={this.context.img} />
  }
}
class UserLogin extends React.Component {
  render() {
    return (
      <div>
        <ThemeContext.Consumer>
          {(theme) => (
            <MyContext.Consumer>
              {(user) => (
                <>
                  {user.name} <button className={`btn btn-${theme.theme}`}>登出</button>
                </>
              )}
            </MyContext.Consumer>
          )}
        </ThemeContext.Consumer>
      </div>
    )
  }
}
const Content = () => {
  return (
    <>
      <h2>内容</h2>
      <SideBar />
    </>
  )
}
const SideBar = () => {
  return (
    <>
      <h2>侧边栏</h2>
      <UserStats />
    </>
  )
}
const UserStats = () => {
  const user = useContext(MyContext)
  const theme = useContext(ThemeContext)
  return (
    <ul>
      {Object.keys(user).map((key) => (
        <li key={key}>
          {key}:{user[key]}
        </li>
      ))}
      <li>当前主题：{theme.theme}</li>
    </ul>
  )
}

const ContextDemo = () => {
  const user = {
    name: '张三',
    level: 99,
    honor: 10273,
    img: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F210611094Q512b-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649301135&t=0569e21a924281ac3cb7138bf0ab0c92',
  }
  const theme = { theme: 'dark' }
  return (
    <>
      <ThemeContext.Provider value={theme}>
        <MyContext.Provider value={user}>
          <Nav />
          <Content />
        </MyContext.Provider>
        <UserLogin />
      </ThemeContext.Provider>
      <UserLogin />
      <UserStats />
    </>
  )
}

export default ContextDemo
